{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2U8rtKk4EI3t"
      },
      "source": [
        "##### Copyright 2020 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "2zIDLJHABcjv"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RgNyvg23XJ7p"
      },
      "source": [
        "# 使用内置方法进行训练和评估"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oxqkOC6o2vgF"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td><a target=\"_blank\" href=\"https://tensorflow.google.cn/guide/keras/train_and_evaluate\" class=\"\"><img src=\"https://tensorflow.google.cn/images/tf_logo_32px.png\" class=\"\">在 TensorFlow.org 上查看</a></td>\n",
        "  <td><a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/keras/train_and_evaluate.ipynb\" class=\"\"><img src=\"https://tensorflow.google.cn/images/colab_logo_32px.png\" class=\"\">在 Google Colab 中运行</a></td>\n",
        "  <td><a target=\"_blank\" href=\"https://github.com/tensorflow/docs-l10n/blob/master/site/zh-cn/guide/keras/train_and_evaluate.ipynb\" class=\"\"><img src=\"https://tensorflow.google.cn/images/GitHub-Mark-32px.png\" class=\"\">在 GitHub 上查看源代码</a></td>\n",
        "  <td><a href=\"https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/zh-cn/guide/keras/train_and_evaluate.ipynb\" class=\"\"><img src=\"https://tensorflow.google.cn/images/download_logo_32px.png\" class=\"\">下载笔记本</a></td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "teOcJ6hnSS5o"
      },
      "source": [
        "## 设置"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mGYBLPAR13g3"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "from tensorflow import keras\n",
        "from tensorflow.keras import layers"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "289cZbiRoKUa"
      },
      "source": [
        "## 简介\n",
        "\n",
        "本指南涵盖使用内置 API 进行训练和验证时需要的训练、评估和预测（推断）模型（例如 `model.fit()`、`model.evaluate()`、`model.predict()`）。\n",
        "\n",
        "如果您有兴趣在指定自己的训练步骤函数时利用 `fit()`，请参阅<a data-md-type=\"link\" href=\"https://tensorflow.google.cn/guide/keras/customizing_what_happens_in_fit/\" class=\"\">“自定义 `fit()` 中发生的操作”</a>指南。\n",
        "\n",
        "如果您有兴趣从头开始编写自己的训练和评估循环，请参阅[“从头开始编写训练循环”](https://tensorflow.google.cn/guide/keras/writing_a_training_loop_from_scratch/)指南。\n",
        "\n",
        "一般而言，无论您使用内置循环还是编写自己的循环，模型训练和评估都会在每种 Keras 模型中严格按照相同的方式工作 -- 序贯模型、使用函数式 API 构建的模型以及通过模型子类化从头编写的模型。\n",
        "\n",
        "本指南不涉及分布式训练。有关分布式训练，请参阅我们的[多 GPU 和分布式训练指南](/guides/distributed_training/)。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wJ51FHNdmeHu"
      },
      "source": [
        "## API 概述：第一个端到端示例\n",
        "\n",
        "将数据传递到模型的内置训练循环时，应当使用 **NumPy 数组**（如果数据很小且适合装入内存）或 **`tf.data Dataset` 对象**。在接下来的段落中，我们将 MNIST 数据集用作 NumPy 数组，以演示如何使用优化器、损失和指标。\n",
        "\n",
        "我们考虑以下模型（在这里，我们使用函数式 API 构建了此模型，但它也可以是序贯模型或子类化模型）："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1GivII8YruI1"
      },
      "outputs": [],
      "source": [
        "inputs = keras.Input(shape=(784,), name=\"digits\")\n",
        "x = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n",
        "x = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\n",
        "outputs = layers.Dense(10, activation=\"softmax\", name=\"predictions\")(x)\n",
        "\n",
        "model = keras.Model(inputs=inputs, outputs=outputs)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Dq8gCsh8cc8m"
      },
      "source": [
        "下面是典型的端到端工作流，包括：\n",
        "\n",
        "- 训练\n",
        "- 根据从原始训练数据生成的预留集进行验证\n",
        "- 根据测试数据进行评估\n",
        "\n",
        "在此示例中，我们使用 MNIST 数据。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WTrVrf4QiojU"
      },
      "outputs": [],
      "source": [
        "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
        "\n",
        "# Preprocess the data (these are NumPy arrays)\n",
        "x_train = x_train.reshape(60000, 784).astype(\"float32\") / 255\n",
        "x_test = x_test.reshape(10000, 784).astype(\"float32\") / 255\n",
        "\n",
        "y_train = y_train.astype(\"float32\")\n",
        "y_test = y_test.astype(\"float32\")\n",
        "\n",
        "# Reserve 10,000 samples for validation\n",
        "x_val = x_train[-10000:]\n",
        "y_val = y_train[-10000:]\n",
        "x_train = x_train[:-10000]\n",
        "y_train = y_train[:-10000]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4kgHixUOrWek"
      },
      "source": [
        "我们指定训练配置（优化器、损失、指标）："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Or9HAqBbBS5m"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(),  # Optimizer\n",
        "    # Loss function to minimize\n",
        "    loss=keras.losses.SparseCategoricalCrossentropy(),\n",
        "    # List of metrics to monitor\n",
        "    metrics=[keras.metrics.SparseCategoricalAccuracy()],\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "36rFtS30q56S"
      },
      "source": [
        "我们调用 `fit()`，它会通过将数据切成大小为“batch_size”的“批次”，然后将整个数据集重复迭代给定数量的“周期”来训练模型。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "yhNJ3Hq30luG"
      },
      "outputs": [],
      "source": [
        "print(\"Fit model on training data\")\n",
        "history = model.fit(\n",
        "    x_train,\n",
        "    y_train,\n",
        "    batch_size=64,\n",
        "    epochs=2,\n",
        "    # We pass some validation for\n",
        "    # monitoring validation loss and metrics\n",
        "    # at the end of each epoch\n",
        "    validation_data=(x_val, y_val),\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Hv6F201DiBVr"
      },
      "source": [
        "返回的“历史”对象保留训练期间的损失值和指标值记录："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "CRP8KiGsxYdO"
      },
      "outputs": [],
      "source": [
        "history.history"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LNuFWerJNjWt"
      },
      "source": [
        "我们通过 `evaluate()` 根据测试数据评估模型："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1tX8Yk2ZryVJ"
      },
      "outputs": [],
      "source": [
        "# Evaluate the model on the test data using `evaluate`\n",
        "print(\"Evaluate on test data\")\n",
        "results = model.evaluate(x_test, y_test, batch_size=128)\n",
        "print(\"test loss, test acc:\", results)\n",
        "\n",
        "# Generate predictions (probabilities -- the output of the last layer)\n",
        "# on new data using `predict`\n",
        "print(\"Generate predictions for 3 samples\")\n",
        "predictions = model.predict(x_test[:3])\n",
        "print(\"predictions shape:\", predictions.shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Ul1Ovpw2uIMa"
      },
      "source": [
        "现在，我们来详细查看此工作流的每一部分。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WxC3o3XOHv7O"
      },
      "source": [
        "## `compile()` 方法：指定损失、指标和优化器\n",
        "\n",
        "要使用 `fit()` 训练模型，您需要指定损失函数、优化器以及一些要监视的指标（可选）。\n",
        "\n",
        "将它们作为 `compile()` 方法的参数传递给模型："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ELAoiVowq4nj"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n",
        "    loss=keras.losses.SparseCategoricalCrossentropy(),\n",
        "    metrics=[keras.metrics.SparseCategoricalAccuracy()],\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RtRJ3EQzQXdq"
      },
      "source": [
        "`metrics` 参数应当为列表 -- 您的模型可以具有任意数量的指标。\n",
        "\n",
        "如果模型具有多个输出，则可以为每个输出指定不同的损失和指标，并且可以调节每个输出对模型总损失的贡献。您可以在**“将数据传递到多输入、多输出模型”**部分中找到有关此内容的更多详细信息。\n",
        "\n",
        "请注意，如果您对默认设置感到满意，那么在许多情况下，都可以通过字符串标识符将优化器、损失和指标指定为捷径："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OsRubkHuXh4u"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer=\"rmsprop\",\n",
        "    loss=\"sparse_categorical_crossentropy\",\n",
        "    metrics=[\"sparse_categorical_accuracy\"],\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TdOjf67OGnZF"
      },
      "source": [
        "为方便以后重用，我们将模型定义和编译步骤放入函数中；我们将在本指南的不同示例中多次调用它们。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mT62JxAkonpb"
      },
      "outputs": [],
      "source": [
        "def get_uncompiled_model():\n",
        "    inputs = keras.Input(shape=(784,), name=\"digits\")\n",
        "    x = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n",
        "    x = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\n",
        "    outputs = layers.Dense(10, activation=\"softmax\", name=\"predictions\")(x)\n",
        "    model = keras.Model(inputs=inputs, outputs=outputs)\n",
        "    return model\n",
        "\n",
        "\n",
        "def get_compiled_model():\n",
        "    model = get_uncompiled_model()\n",
        "    model.compile(\n",
        "        optimizer=\"rmsprop\",\n",
        "        loss=\"sparse_categorical_crossentropy\",\n",
        "        metrics=[\"sparse_categorical_accuracy\"],\n",
        "    )\n",
        "    return model\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8KIw3lKFY4v3"
      },
      "source": [
        "### 提供许多内置优化器、损失和指标\n",
        "\n",
        "通常，您不必从头开始创建自己的损失、指标或优化器，因为您需要的可能已经是 Keras API 的一部分：\n",
        "\n",
        "优化器：\n",
        "\n",
        "- `SGD()`（有或没有动量）\n",
        "- `RMSprop()`\n",
        "- `Adam()`\n",
        "- 等等\n",
        "\n",
        "损失：\n",
        "\n",
        "- `MeanSquaredError()`\n",
        "- `KLDivergence()`\n",
        "- `CosineSimilarity()`\n",
        "- 等等\n",
        "\n",
        "指标：\n",
        "\n",
        "- `AUC()`\n",
        "- `Precision()`\n",
        "- `Recall()`\n",
        "- 等等"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hTth4Ksz1cDr"
      },
      "source": [
        "### 自定义损失\n",
        "\n",
        "有两种方法来使用 Keras 提供自定义损失。第一个示例创建一个接受输入 `y_true` 和 `y_pred` 的函数。下面的示例显示了一个计算实际数据与预测值之间的均方误差的损失函数："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "EAuZtRoViEtN"
      },
      "outputs": [],
      "source": [
        "def custom_mean_squared_error(y_true, y_pred):\n",
        "    return tf.math.reduce_mean(tf.square(y_true - y_pred))\n",
        "\n",
        "\n",
        "model = get_uncompiled_model()\n",
        "model.compile(optimizer=keras.optimizers.Adam(), loss=custom_mean_squared_error)\n",
        "\n",
        "# We need to one-hot encode the labels to use MSE\n",
        "y_train_one_hot = tf.one_hot(y_train, depth=10)\n",
        "model.fit(x_train, y_train_one_hot, batch_size=64, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BHbC8v5AYTUy"
      },
      "source": [
        "如果您需要一个使用除 `y_true` 和 `y_pred` 之外的其他参数的损失函数，则可以将 `tf.keras.losses.Loss` 类子类化，并实现以下两个方法：\n",
        "\n",
        "- `__init__(self)`：接受要在调用损失函数期间传递的参数\n",
        "- `call(self, y_true, y_pred)`：使用目标 (y_true) 和模型预测 (y_pred) 来计算模型的损失\n",
        "\n",
        "假设您要使用均方误差，但存在一个会抑制预测值远离 0.5（我们假设分类目标采用独热编码，且取值介于 0 和 1 之间）的附加项。这会为模型创建一个激励，使其不会对预测值过于自信，这可能有助于减轻过拟合（在尝试之前，我们不知道它是否有效！）。\n",
        "\n",
        "您可以按以下方式处理："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wEOeF6UqgEvG"
      },
      "outputs": [],
      "source": [
        "class CustomMSE(keras.losses.Loss):\n",
        "    def __init__(self, regularization_factor=0.1, name=\"custom_mse\"):\n",
        "        super().__init__(name=name)\n",
        "        self.regularization_factor = regularization_factor\n",
        "\n",
        "    def call(self, y_true, y_pred):\n",
        "        mse = tf.math.reduce_mean(tf.square(y_true - y_pred))\n",
        "        reg = tf.math.reduce_mean(tf.square(0.5 - y_pred))\n",
        "        return mse + reg * self.regularization_factor\n",
        "\n",
        "\n",
        "model = get_uncompiled_model()\n",
        "model.compile(optimizer=keras.optimizers.Adam(), loss=CustomMSE())\n",
        "\n",
        "y_train_one_hot = tf.one_hot(y_train, depth=10)\n",
        "model.fit(x_train, y_train_one_hot, batch_size=64, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wdoCA46g3HPg"
      },
      "source": [
        "### 自定义指标\n",
        "\n",
        "如果您需要不属于 API 的指标，则可以通过将 `tf.keras.metrics.Metric` 类子类化来轻松创建自定义指标。您将需要实现 4 个方法：\n",
        "\n",
        "- `__init__(self)`，您将在其中为指标创建状态变量。\n",
        "- `update_state(self, y_true, y_pred, sample_weight=None)`，使用目标 y_true 和模型预测 y_pred 更新状态变量。\n",
        "- `result(self)`，使用状态变量来计算最终结果。\n",
        "- `reset_states(self)`，用于重新初始化指标的状态。\n",
        "\n",
        "状态更新和结果计算分开保存（分别保存在 `update_state()` 和 `result()` 中），因为在某些情况下，结果计算的开销可能会非常大，并且只能定期执行。\n",
        "\n",
        "下面是一个展示如何实现 `CategoricalTruePositives` 指标的简单示例，该指标可以计算有多少样本被正确分类为属于给定类："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f6hNnE0Xz945"
      },
      "outputs": [],
      "source": [
        "class CategoricalTruePositives(keras.metrics.Metric):\n",
        "    def __init__(self, name=\"categorical_true_positives\", **kwargs):\n",
        "        super(CategoricalTruePositives, self).__init__(name=name, **kwargs)\n",
        "        self.true_positives = self.add_weight(name=\"ctp\", initializer=\"zeros\")\n",
        "\n",
        "    def update_state(self, y_true, y_pred, sample_weight=None):\n",
        "        y_pred = tf.reshape(tf.argmax(y_pred, axis=1), shape=(-1, 1))\n",
        "        values = tf.cast(y_true, \"int32\") == tf.cast(y_pred, \"int32\")\n",
        "        values = tf.cast(values, \"float32\")\n",
        "        if sample_weight is not None:\n",
        "            sample_weight = tf.cast(sample_weight, \"float32\")\n",
        "            values = tf.multiply(values, sample_weight)\n",
        "        self.true_positives.assign_add(tf.reduce_sum(values))\n",
        "\n",
        "    def result(self):\n",
        "        return self.true_positives\n",
        "\n",
        "    def reset_states(self):\n",
        "        # The state of the metric will be reset at the start of each epoch.\n",
        "        self.true_positives.assign(0.0)\n",
        "\n",
        "\n",
        "model = get_uncompiled_model()\n",
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n",
        "    loss=keras.losses.SparseCategoricalCrossentropy(),\n",
        "    metrics=[CategoricalTruePositives()],\n",
        ")\n",
        "model.fit(x_train, y_train, batch_size=64, epochs=3)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XSC3upuYsZJf"
      },
      "source": [
        "### 处理不适合标准签名的损失和指标\n",
        "\n",
        "可以根据 `y_true` 和 `y_pred` 计算出绝大多数损失和指标，其中 `y_pred` 是模型的输出。不过，仍有一些损失和指标无法计算，例如，正则化损失可能仅需要激活层（这种情况下没有目标），并且此激活可能不是模型输出。\n",
        "\n",
        "在这种情况下，您可以从自定义层的调用方法内部调用 `self.add_loss(loss_value)`。以这种方式添加的损失会在训练期间添加到“主要”损失中（传递给 `compile()` 的损失）。下面是一个添加激活正则化的简单示例（请注意，激活正则化内置于所有 Keras 层中 -- 该层只是为了提供一个具体示例）："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "uEoMY1baigwm"
      },
      "outputs": [],
      "source": [
        "class ActivityRegularizationLayer(layers.Layer):\n",
        "    def call(self, inputs):\n",
        "        self.add_loss(tf.reduce_sum(inputs) * 0.1)\n",
        "        return inputs  # Pass-through layer.\n",
        "\n",
        "\n",
        "inputs = keras.Input(shape=(784,), name=\"digits\")\n",
        "x = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n",
        "\n",
        "# Insert activity regularization as a layer\n",
        "x = ActivityRegularizationLayer()(x)\n",
        "\n",
        "x = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\n",
        "outputs = layers.Dense(10, name=\"predictions\")(x)\n",
        "\n",
        "model = keras.Model(inputs=inputs, outputs=outputs)\n",
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n",
        "    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        ")\n",
        "\n",
        "# The displayed loss will be much higher than before\n",
        "# due to the regularization component.\n",
        "model.fit(x_train, y_train, batch_size=64, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LOrHwOqG5z0I"
      },
      "source": [
        "您可以使用 `add_metric()` 对记录指标值执行相同的操作："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jJlqaoWBItbV"
      },
      "outputs": [],
      "source": [
        "class MetricLoggingLayer(layers.Layer):\n",
        "    def call(self, inputs):\n",
        "        # The `aggregation` argument defines\n",
        "        # how to aggregate the per-batch values\n",
        "        # over each epoch:\n",
        "        # in this case we simply average them.\n",
        "        self.add_metric(\n",
        "            keras.backend.std(inputs), name=\"std_of_activation\", aggregation=\"mean\"\n",
        "        )\n",
        "        return inputs  # Pass-through layer.\n",
        "\n",
        "\n",
        "inputs = keras.Input(shape=(784,), name=\"digits\")\n",
        "x = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n",
        "\n",
        "# Insert std logging as a layer.\n",
        "x = MetricLoggingLayer()(x)\n",
        "\n",
        "x = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x)\n",
        "outputs = layers.Dense(10, name=\"predictions\")(x)\n",
        "\n",
        "model = keras.Model(inputs=inputs, outputs=outputs)\n",
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n",
        "    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        ")\n",
        "model.fit(x_train, y_train, batch_size=64, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8f7FBpwJOJAS"
      },
      "source": [
        "在[函数式 API](https://tensorflow.google.cn/guide/keras/functional/) 中，您还可以调用 `model.add_loss(loss_tensor)` 或 `model.add_metric(metric_tensor, name, aggregation)`。\n",
        "\n",
        "下面是一个简单的示例："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "voJumeU4louI"
      },
      "outputs": [],
      "source": [
        "inputs = keras.Input(shape=(784,), name=\"digits\")\n",
        "x1 = layers.Dense(64, activation=\"relu\", name=\"dense_1\")(inputs)\n",
        "x2 = layers.Dense(64, activation=\"relu\", name=\"dense_2\")(x1)\n",
        "outputs = layers.Dense(10, name=\"predictions\")(x2)\n",
        "model = keras.Model(inputs=inputs, outputs=outputs)\n",
        "\n",
        "model.add_loss(tf.reduce_sum(x1) * 0.1)\n",
        "\n",
        "model.add_metric(keras.backend.std(x1), name=\"std_of_activation\", aggregation=\"mean\")\n",
        "\n",
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
        "    loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        ")\n",
        "model.fit(x_train, y_train, batch_size=64, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hIg9AQ8fiku4"
      },
      "source": [
        "请注意，当您通过 `add_loss()` 传递损失时，可以在没有损失函数的情况下调用 `compile()`，因为模型已经有损失要最小化。\n",
        "\n",
        "考虑以下 `LogisticEndpoint` 层：它以目标和 logits 作为输入，并通过 `add_loss()` 跟踪交叉熵损失。另外，它还通过 `add_metric()` 跟踪分类准确率。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cmpAV3nY6WRR"
      },
      "outputs": [],
      "source": [
        "class LogisticEndpoint(keras.layers.Layer):\n",
        "    def __init__(self, name=None):\n",
        "        super(LogisticEndpoint, self).__init__(name=name)\n",
        "        self.loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)\n",
        "        self.accuracy_fn = keras.metrics.BinaryAccuracy()\n",
        "\n",
        "    def call(self, targets, logits, sample_weights=None):\n",
        "        # Compute the training-time loss value and add it\n",
        "        # to the layer using `self.add_loss()`.\n",
        "        loss = self.loss_fn(targets, logits, sample_weights)\n",
        "        self.add_loss(loss)\n",
        "\n",
        "        # Log accuracy as a metric and add it\n",
        "        # to the layer using `self.add_metric()`.\n",
        "        acc = self.accuracy_fn(targets, logits, sample_weights)\n",
        "        self.add_metric(acc, name=\"accuracy\")\n",
        "\n",
        "        # Return the inference-time prediction tensor (for `.predict()`).\n",
        "        return tf.nn.softmax(logits)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yhpJo97oNuVx"
      },
      "source": [
        "您可以在具有两个输入（输入数据和目标）的模型中使用它，编译时无需 `loss` 参数，如下所示："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "tpYO0EuZf3c1"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "inputs = keras.Input(shape=(3,), name=\"inputs\")\n",
        "targets = keras.Input(shape=(10,), name=\"targets\")\n",
        "logits = keras.layers.Dense(10)(inputs)\n",
        "predictions = LogisticEndpoint(name=\"predictions\")(logits, targets)\n",
        "\n",
        "model = keras.Model(inputs=[inputs, targets], outputs=predictions)\n",
        "model.compile(optimizer=\"adam\")  # No loss argument!\n",
        "\n",
        "data = {\n",
        "    \"inputs\": np.random.random((3, 3)),\n",
        "    \"targets\": np.random.random((3, 10)),\n",
        "}\n",
        "model.fit(data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e9ATCfOObGXh"
      },
      "source": [
        "有关训练多输入模型的更多信息，请参阅**将数据传递到多输入、多输出模型**部分。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OJ3XxUkOCJDA"
      },
      "source": [
        "### 自动分离验证预留集\n",
        "\n",
        "在您看到的第一个端到端示例中，我们使用了 `validation_data` 参数将 NumPy 数组 `(x_val, y_val)` 的元组传递给模型，用于在每个周期结束时评估验证损失和验证指标。\n",
        "\n",
        "这是另一个选项：参数 `validation_split` 允许您自动保留部分训练数据以供验证。参数值表示要保留用于验证的数据比例，因此应将其设置为大于 0 且小于 1 的数字。例如，`validation_split=0.2` 表示“使用 20% 的数据进行验证”，而 `validation_split=0.6` 表示“使用 60% 的数据进行验证”。\n",
        "\n",
        "验证的计算方式为：在任何乱序之前，抽取通过 fit 调用接收的数组最后 x% 的样本。\n",
        "\n",
        "请注意，仅在使用 NumPy 数据进行训练时才能使用 `validation_split`。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "TraQan0uov0T"
      },
      "outputs": [],
      "source": [
        "model = get_compiled_model()\n",
        "model.fit(x_train, y_train, batch_size=64, validation_split=0.2, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "M4WbEioWqf2j"
      },
      "source": [
        "## 通过 tf.data 数据集进行训练和评估\n",
        "\n",
        "在前面的几个段落中，您已经了解如何处理损失、指标和优化器，并且已经知道在将数据作为 NumPy 数组传递时如何在 fit 中使用 `validation_data` 和 `validation_split` 参数。\n",
        "\n",
        "现在，让我们看一下数据以 `tf.data.Dataset` 对象形式出现的情况。\n",
        "\n",
        "`tf.data` API是 TensorFlow 2.0 中的一组实用工具，用于以快速且可扩展的方式加载和预处理数据。\n",
        "\n",
        "有关创建 `Datasets` 的完整指南，请参阅 [tf.data 文档](https://tensorflow.google.cn/guide/data)。\n",
        "\n",
        "您可以将 `Dataset` 实例直接传递给 `fit()`、`evaluate()` 和 `predict()`："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "t213jBqAFwb5"
      },
      "outputs": [],
      "source": [
        "model = get_compiled_model()\n",
        "\n",
        "# First, let's create a training Dataset instance.\n",
        "# For the sake of our example, we'll use the same MNIST data as before.\n",
        "train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n",
        "# Shuffle and slice the dataset.\n",
        "train_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n",
        "\n",
        "# Now we get a test dataset.\n",
        "test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))\n",
        "test_dataset = test_dataset.batch(64)\n",
        "\n",
        "# Since the dataset already takes care of batching,\n",
        "# we don't pass a `batch_size` argument.\n",
        "model.fit(train_dataset, epochs=3)\n",
        "\n",
        "# You can also evaluate or predict on a dataset.\n",
        "print(\"Evaluate\")\n",
        "result = model.evaluate(test_dataset)\n",
        "dict(zip(model.metrics_names, result))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3f3Y65TiYoap"
      },
      "source": [
        "请注意，数据集会在每个周期结束时重置，因此可以在下一个周期重复使用。\n",
        "\n",
        "如果您只想在来自此数据集的特定数量批次上进行训练，则可以传递 `steps_per_epoch` 参数，此参数可以指定在继续下一个周期之前，模型应使用此数据集运行多少训练步骤。\n",
        "\n",
        "如果执行此操作，则不会在每个周期结束时重置数据集，而是会继续绘制接下来的批次。数据集最终将用尽数据（除非它是无限循环的数据集）。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ycoSkTq0J5kR"
      },
      "outputs": [],
      "source": [
        "model = get_compiled_model()\n",
        "\n",
        "# Prepare the training dataset\n",
        "train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n",
        "train_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n",
        "\n",
        "# Only use the 100 batches per epoch (that's 64 * 100 samples)\n",
        "model.fit(train_dataset, epochs=3, steps_per_epoch=100)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7prZFnId4Xru"
      },
      "source": [
        "### 使用验证数据集\n",
        "\n",
        "您可以在 `fit()` 中将 `Dataset` 实例作为 `validation_data` 参数传递："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ET87Q427EbNM"
      },
      "outputs": [],
      "source": [
        "model = get_compiled_model()\n",
        "\n",
        "# Prepare the training dataset\n",
        "train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n",
        "train_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n",
        "\n",
        "# Prepare the validation dataset\n",
        "val_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))\n",
        "val_dataset = val_dataset.batch(64)\n",
        "\n",
        "model.fit(train_dataset, epochs=1, validation_data=val_dataset)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zCWuTgqZ6sPe"
      },
      "source": [
        "在每个周期结束时，模型将迭代验证数据集并计算验证损失和验证指标。\n",
        "\n",
        "如果只想对此数据集中的特定数量批次运行验证，则可以传递 `validation_steps` 参数，此参数可以指定在中断验证并进入下一个周期之前，模型应使用验证数据集运行多少验证步骤："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "esU1Cr1O9rOc"
      },
      "outputs": [],
      "source": [
        "model = get_compiled_model()\n",
        "\n",
        "# Prepare the training dataset\n",
        "train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n",
        "train_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n",
        "\n",
        "# Prepare the validation dataset\n",
        "val_dataset = tf.data.Dataset.from_tensor_slices((x_val, y_val))\n",
        "val_dataset = val_dataset.batch(64)\n",
        "\n",
        "model.fit(\n",
        "    train_dataset,\n",
        "    epochs=1,\n",
        "    # Only run validation using the first 10 batches of the dataset\n",
        "    # using the `validation_steps` argument\n",
        "    validation_data=val_dataset,\n",
        "    validation_steps=10,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "y4n3HmmQ1cSh"
      },
      "source": [
        "请注意，验证数据集将在每次使用后重置（这样您就可以在不同周期中始终根据相同的样本进行评估）。\n",
        "\n",
        "通过 `Dataset` 对象进行训练时，不支持参数 `validation_split`（从训练数据生成预留集），因为此功能需要为数据集样本编制索引的能力，而 `Dataset` API 通常无法做到这一点。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pOI6qq7qvl3S"
      },
      "source": [
        "## 支持的其他输入格式\n",
        "\n",
        "除 NumPy 数组、Eager 张量和 TensorFlow `Datasets` 外，还可以使用 Pandas 数据帧或通过产生批量数据和标签的 Python 生成器训练 Keras 模型。\n",
        "\n",
        "特别是，`keras.utils.Sequence` 类提供了一个简单的接口来构建可感知多处理并且可以打乱顺序的 Python 数据生成器。\n",
        "\n",
        "通常，我们建议您使用：\n",
        "\n",
        "- NumPy 输入数据，前提是您的数据很小且适合装入内存\n",
        "- `Dataset` 对象，前提是您有大型数据集，且需要执行分布式训练\n",
        "- `Sequence` 对象，前提是您具有大型数据集，且需要执行很多无法在 TensorFlow 中完成的自定义 Python 端处理（例如，如果您依赖外部库进行数据加载或预处理）。\n",
        "\n",
        "## 使用 `keras.utils.Sequence` 对象作为输入\n",
        "\n",
        "`keras.utils.Sequence` 是一个实用工具，您可以将其子类化以获得具有两个重要属性的 Python 生成器：\n",
        "\n",
        "- 它适用于多处理。\n",
        "- 可以打乱它的顺序（例如，在 `fit()` 中传递 `shuffle=True` 时）。\n",
        "\n",
        "`Sequence` 必须实现两个方法：\n",
        "\n",
        "- `__getitem__`\n",
        "- `__len__`\n",
        "\n",
        "`__getitem__` 方法应返回完整的批次。如果要在各个周期之间修改数据集，可以实现 `on_epoch_end`。\n",
        "\n",
        "下面是一个简单的示例：\n",
        "\n",
        "```python\n",
        "from skimage.io import imread\n",
        "from skimage.transform import resize\n",
        "import numpy as np\n",
        "\n",
        "# Here, `filenames` is list of path to the images\n",
        "# and `labels` are the associated labels.\n",
        "\n",
        "class CIFAR10Sequence(Sequence):\n",
        "    def __init__(self, filenames, labels, batch_size):\n",
        "        self.filenames, self.labels = filenames, labels\n",
        "        self.batch_size = batch_size\n",
        "\n",
        "    def __len__(self):\n",
        "        return int(np.ceil(len(self.filenames) / float(self.batch_size)))\n",
        "\n",
        "    def __getitem__(self, idx):\n",
        "        batch_x = self.filenames[idx * self.batch_size:(idx + 1) * self.batch_size]\n",
        "        batch_y = self.labels[idx * self.batch_size:(idx + 1) * self.batch_size]\n",
        "        return np.array([\n",
        "            resize(imread(filename), (200, 200))\n",
        "               for filename in batch_x]), np.array(batch_y)\n",
        "\n",
        "sequence = CIFAR10Sequence(filenames, labels, batch_size)\n",
        "model.fit(sequence, epochs=10)\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YTY1mCJ6F03i"
      },
      "source": [
        "## 使用样本加权和类加权\n",
        "\n",
        "在默认设置下，样本的权重由其在数据集中出现的频率决定。有两种方法可以独立于样本频率来加权数据：\n",
        "\n",
        "- 类权重\n",
        "- 样本权重"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fjggBDd7IzeZ"
      },
      "source": [
        "### 类权重\n",
        "\n",
        "通过将字典传递给 `Model.fit()` 的 `class_weight` 参数来进行设置。此字典会将类索引映射到应当用于属于此类的样本的权重。\n",
        "\n",
        "这可用于在不重采样的情况下平衡类，或者用于训练更加重视特定类的模型。\n",
        "\n",
        "例如，在您的数据中，如果类“0”表示类“1”的一半，则可以使用 `Model.fit(..., class_weight={0: 1., 1: 0.5})`。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xGa65BdyLdy6"
      },
      "source": [
        "下面是一个 NumPy 示例，我们在其中使用类权重或样本权重来提高对类 #5（MNIST 数据集中的数字“5”）进行正确分类的重要性。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oPBuPHqYIqum"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "\n",
        "class_weight = {\n",
        "    0: 1.0,\n",
        "    1: 1.0,\n",
        "    2: 1.0,\n",
        "    3: 1.0,\n",
        "    4: 1.0,\n",
        "    # Set weight \"2\" for class \"5\",\n",
        "    # making this class 2x more important\n",
        "    5: 2.0,\n",
        "    6: 1.0,\n",
        "    7: 1.0,\n",
        "    8: 1.0,\n",
        "    9: 1.0,\n",
        "}\n",
        "\n",
        "print(\"Fit with class weight\")\n",
        "model = get_compiled_model()\n",
        "model.fit(x_train, y_train, class_weight=class_weight, batch_size=64, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DclU4GWLjuCN"
      },
      "source": [
        "### 样本权重\n",
        "\n",
        "对于细粒度控制，或者如果您不构建分类器，则可以使用“样本权重”。\n",
        "\n",
        "- 通过 NumPy 数据进行训练时：将 `sample_weight` 参数传递给 `Model.fit()`。\n",
        "- 通过 `tf.data` 或任何其他类型的迭代器进行训练时：产生 `(input_batch, label_batch, sample_weight_batch)` 元组。\n",
        "\n",
        "“样本权重”数组是一个由数字组成的数组，这些数字用于指定批次中每个样本在计算总损失时应当具有的权重。它通常用于不平衡的分类问题（理念是将更多权重分配给罕见类）。\n",
        "\n",
        "当使用的权重为 1 和 0 时，此数组可用作损失函数的*掩码*（完全丢弃某些样本对总损失的贡献）。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oceIUhLclV5i"
      },
      "outputs": [],
      "source": [
        "sample_weight = np.ones(shape=(len(y_train),))\n",
        "sample_weight[y_train == 5] = 2.0\n",
        "\n",
        "print(\"Fit with sample weight\")\n",
        "model = get_compiled_model()\n",
        "model.fit(x_train, y_train, sample_weight=sample_weight, batch_size=64, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Z3yZvJwG7hMo"
      },
      "source": [
        "下面是一个匹配的 `Dataset` 示例："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "RC8WB7BVM2ty"
      },
      "outputs": [],
      "source": [
        "sample_weight = np.ones(shape=(len(y_train),))\n",
        "sample_weight[y_train == 5] = 2.0\n",
        "\n",
        "# Create a Dataset that includes sample weights\n",
        "# (3rd element in the return tuple).\n",
        "train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train, sample_weight))\n",
        "\n",
        "# Shuffle and slice the dataset.\n",
        "train_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n",
        "\n",
        "model = get_compiled_model()\n",
        "model.fit(train_dataset, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lp36RvM6jxrY"
      },
      "source": [
        "## 将数据传递到多输入、多输出模型\n",
        "\n",
        "在前面的示例中，我们考虑的是具有单个输入（形状 `(764,)` 的张量）和单个输出（形状 `(10,)` 的预测张量）的模型。但具有多个输入或输出的模型呢？\n",
        "\n",
        "考虑以下模型，该模型具有形状为 `(32, 32, 3)` 的图像输入（即 `(height, width, channels)`）和形状为 `(None, 10)` 的时间序列输入（即 `(timesteps, features)`）。我们的模型将具有根据这些输入的组合计算出的两个输出：“得分”（形状为 `(1,)`）和在五个类上的概率分布（形状为 `(5,)`）。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ntmviPVuPI7D"
      },
      "outputs": [],
      "source": [
        "image_input = keras.Input(shape=(32, 32, 3), name=\"img_input\")\n",
        "timeseries_input = keras.Input(shape=(None, 10), name=\"ts_input\")\n",
        "\n",
        "x1 = layers.Conv2D(3, 3)(image_input)\n",
        "x1 = layers.GlobalMaxPooling2D()(x1)\n",
        "\n",
        "x2 = layers.Conv1D(3, 3)(timeseries_input)\n",
        "x2 = layers.GlobalMaxPooling1D()(x2)\n",
        "\n",
        "x = layers.concatenate([x1, x2])\n",
        "\n",
        "score_output = layers.Dense(1, name=\"score_output\")(x)\n",
        "class_output = layers.Dense(5, activation=\"softmax\", name=\"class_output\")(x)\n",
        "\n",
        "model = keras.Model(\n",
        "    inputs=[image_input, timeseries_input], outputs=[score_output, class_output]\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "BXeG97WpnPJr"
      },
      "source": [
        "我们来绘制这个模型，以便您可以清楚地看到我们在这里执行的操作（请注意，图中显示的形状是批次形状，而不是每个样本的形状）。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "lzrnY3xo79iA"
      },
      "outputs": [],
      "source": [
        "keras.utils.plot_model(model, \"multi_input_and_output_model.png\", show_shapes=True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nAXWeBnT0COk"
      },
      "source": [
        "在编译时，通过将损失函数作为列表传递，我们可以为不同的输出指定不同的损失："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Dd2abNMC7XrP"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
        "    loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "B6i258rpl0Lv"
      },
      "source": [
        "如果我们仅将单个损失函数传递给模型，则相同的损失函数将应用于每个输出（此处不合适）。\n",
        "\n",
        "对于指标同样如此："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "iTHQ2ULuVsQM"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
        "    loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n",
        "    metrics=[\n",
        "        [\n",
        "            keras.metrics.MeanAbsolutePercentageError(),\n",
        "            keras.metrics.MeanAbsoluteError(),\n",
        "        ],\n",
        "        [keras.metrics.CategoricalAccuracy()],\n",
        "    ],\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UsFMZWYxwqbM"
      },
      "source": [
        "由于我们已为输出层命名，我们还可以通过字典指定每个输出的损失和指标："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Pr9RN6wGr1FN"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
        "    loss={\n",
        "        \"score_output\": keras.losses.MeanSquaredError(),\n",
        "        \"class_output\": keras.losses.CategoricalCrossentropy(),\n",
        "    },\n",
        "    metrics={\n",
        "        \"score_output\": [\n",
        "            keras.metrics.MeanAbsolutePercentageError(),\n",
        "            keras.metrics.MeanAbsoluteError(),\n",
        "        ],\n",
        "        \"class_output\": [keras.metrics.CategoricalAccuracy()],\n",
        "    },\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NTiNnyjiJe5P"
      },
      "source": [
        "如果您的输出超过 2 个，我们建议使用显式名称和字典。\n",
        "\n",
        "可以使用 `loss_weights` 参数为特定于输出的不同损失赋予不同的权重（例如，在我们的示例中，我们可能希望通过为类损失赋予 2 倍重要性来向“得分”损失赋予特权）："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pg2puZ5KvBKw"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
        "    loss={\n",
        "        \"score_output\": keras.losses.MeanSquaredError(),\n",
        "        \"class_output\": keras.losses.CategoricalCrossentropy(),\n",
        "    },\n",
        "    metrics={\n",
        "        \"score_output\": [\n",
        "            keras.metrics.MeanAbsolutePercentageError(),\n",
        "            keras.metrics.MeanAbsoluteError(),\n",
        "        ],\n",
        "        \"class_output\": [keras.metrics.CategoricalAccuracy()],\n",
        "    },\n",
        "    loss_weights={\"score_output\": 2.0, \"class_output\": 1.0},\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "k9MUn5WXtatT"
      },
      "source": [
        "您还可以选择不为某些输出计算损失，前提是这些输出仅用于预测而不是训练："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wq2Ecw9oeLVl"
      },
      "outputs": [],
      "source": [
        "# List loss version\n",
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
        "    loss=[None, keras.losses.CategoricalCrossentropy()],\n",
        ")\n",
        "\n",
        "# Or dict loss version\n",
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
        "    loss={\"class_output\": keras.losses.CategoricalCrossentropy()},\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ZqsjpRqsnORf"
      },
      "source": [
        "在 fit 中将数据传递给多输入或多输出模型的方式与在编译中指定损失函数的方式类似：您可以传递 **NumPy 数组的列表**（以 1:1 映射到接收损失函数的输出）或**将输出名称映射到 NumPy 数组的字典**。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "LIftd9mSB81g"
      },
      "outputs": [],
      "source": [
        "model.compile(\n",
        "    optimizer=keras.optimizers.RMSprop(1e-3),\n",
        "    loss=[keras.losses.MeanSquaredError(), keras.losses.CategoricalCrossentropy()],\n",
        ")\n",
        "\n",
        "# Generate dummy NumPy data\n",
        "img_data = np.random.random_sample(size=(100, 32, 32, 3))\n",
        "ts_data = np.random.random_sample(size=(100, 20, 10))\n",
        "score_targets = np.random.random_sample(size=(100, 1))\n",
        "class_targets = np.random.random_sample(size=(100, 5))\n",
        "\n",
        "# Fit on lists\n",
        "model.fit([img_data, ts_data], [score_targets, class_targets], batch_size=32, epochs=1)\n",
        "\n",
        "# Alternatively, fit on dicts\n",
        "model.fit(\n",
        "    {\"img_input\": img_data, \"ts_input\": ts_data},\n",
        "    {\"score_output\": score_targets, \"class_output\": class_targets},\n",
        "    batch_size=32,\n",
        "    epochs=1,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VNzcGRy1WiDc"
      },
      "source": [
        "下面是 `Dataset` 的用例：与我们对 NumPy 数组执行的操作类似，`Dataset` 应返回一个字典元组。"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4YVlRTcpwknb"
      },
      "outputs": [],
      "source": [
        "train_dataset = tf.data.Dataset.from_tensor_slices(\n",
        "    (\n",
        "        {\"img_input\": img_data, \"ts_input\": ts_data},\n",
        "        {\"score_output\": score_targets, \"class_output\": class_targets},\n",
        "    )\n",
        ")\n",
        "train_dataset = train_dataset.shuffle(buffer_size=1024).batch(64)\n",
        "\n",
        "model.fit(train_dataset, epochs=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "R4CsiI5H2HQ9"
      },
      "source": [
        "## 使用回调\n",
        "\n",
        "Keras 中的回调是训练期间（某个周期开始时、某个批次结束时、某个周期结束时等）在不同时间点调用的对象，这些对象可用于实现以下行为：\n",
        "\n",
        "- 在训练期间的不同时间点进行验证（除了内置的按周期验证外）\n",
        "- 定期或在超过一定准确率阈值时为模型设置检查点\n",
        "- 当训练似乎停滞不前时，更改模型的学习率\n",
        "- 当训练似乎停滞不前时，对顶层进行微调\n",
        "- 在训练结束或超出特定性能阈值时发送电子邮件或即时消息通知\n",
        "- 等等\n",
        "\n",
        "回调可以作为列表传递给您对 `fit()` 的调用："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "kOArJW1vXhEl"
      },
      "outputs": [],
      "source": [
        "model = get_compiled_model()\n",
        "\n",
        "callbacks = [\n",
        "    keras.callbacks.EarlyStopping(\n",
        "        # Stop training when `val_loss` is no longer improving\n",
        "        monitor=\"val_loss\",\n",
        "        # \"no longer improving\" being defined as \"no better than 1e-2 less\"\n",
        "        min_delta=1e-2,\n",
        "        # \"no longer improving\" being further defined as \"for at least 2 epochs\"\n",
        "        patience=2,\n",
        "        verbose=1,\n",
        "    )\n",
        "]\n",
        "model.fit(\n",
        "    x_train,\n",
        "    y_train,\n",
        "    epochs=20,\n",
        "    batch_size=64,\n",
        "    callbacks=callbacks,\n",
        "    validation_split=0.2,\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EGl2HS9QjLwu"
      },
      "source": [
        "### 提供多个内置回调\n",
        "\n",
        "- `ModelCheckpoint`：定期保存模型。\n",
        "- `EarlyStopping`：当训练不再改善验证指标时，停止训练。\n",
        "-  `TensorBoard`：定期编写可在 [TensorBoard](https://tensorflow.google.cn/tensorboard) 中可视化的模型日志（更多详细信息，请参阅“可视化”部分）。\n",
        "- `CSVLogger`：将损失和指标数据流式传输到 CSV 文件。\n",
        "- 等等\n",
        "\n",
        "有关完整列表，请参阅[回调文档](https://tensorflow.google.cn/api_docs/python/tf/keras/callbacks/)。\n",
        "\n",
        "### 编写您自己的回调\n",
        "\n",
        "您可以通过扩展基类 `keras.callbacks.Callback` 来创建自定义回调。回调可以通过类属性 `self.model` 访问其关联的模型。\n",
        "\n",
        "确保阅读[编写自定义回调的完整指南](https://tensorflow.google.cn/guide/keras/custom_callback/)。\n",
        "\n",
        "下面是一个简单的示例，在训练期间保存每个批次的损失值列表："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xbr9eYTtAfg9"
      },
      "outputs": [],
      "source": [
        "class LossHistory(keras.callbacks.Callback):\n",
        "    def on_train_begin(self, logs):\n",
        "        self.per_batch_losses = []\n",
        "\n",
        "    def on_batch_end(self, batch, logs):\n",
        "        self.per_batch_losses.append(logs.get(\"loss\"))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mfBuL1RfYWYu"
      },
      "source": [
        "## 为模型设置检查点\n",
        "\n",
        "根据相对较大的数据集训练模型时，经常保存模型的检查点至关重要。\n",
        "\n",
        "实现此目标的最简单方法是使用 `ModelCheckpoint` 回调："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZJGVnZDOgCGz"
      },
      "outputs": [],
      "source": [
        "model = get_compiled_model()\n",
        "\n",
        "callbacks = [\n",
        "    keras.callbacks.ModelCheckpoint(\n",
        "        # Path where to save the model\n",
        "        # The two parameters below mean that we will overwrite\n",
        "        # the current checkpoint if and only if\n",
        "        # the `val_loss` score has improved.\n",
        "        # The saved model name will include the current epoch.\n",
        "        filepath=\"mymodel_{epoch}\",\n",
        "        save_best_only=True,  # Only save a model if `val_loss` has improved.\n",
        "        monitor=\"val_loss\",\n",
        "        verbose=1,\n",
        "    )\n",
        "]\n",
        "model.fit(\n",
        "    x_train, y_train, epochs=2, batch_size=64, callbacks=callbacks, validation_split=0.2\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vlzo8T5ecYEa"
      },
      "source": [
        "`ModelCheckpoint` 回调可用于实现容错：在训练随机中断的情况下，从模型的最后保存状态重新开始训练的能力。下面是一个基本示例："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5lcqi3mWcaFK"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "# Prepare a directory to store all the checkpoints.\n",
        "checkpoint_dir = \"./ckpt\"\n",
        "if not os.path.exists(checkpoint_dir):\n",
        "    os.makedirs(checkpoint_dir)\n",
        "\n",
        "\n",
        "def make_or_restore_model():\n",
        "    # Either restore the latest model, or create a fresh one\n",
        "    # if there is no checkpoint available.\n",
        "    checkpoints = [checkpoint_dir + \"/\" + name for name in os.listdir(checkpoint_dir)]\n",
        "    if checkpoints:\n",
        "        latest_checkpoint = max(checkpoints, key=os.path.getctime)\n",
        "        print(\"Restoring from\", latest_checkpoint)\n",
        "        return keras.models.load_model(latest_checkpoint)\n",
        "    print(\"Creating a new model\")\n",
        "    return get_compiled_model()\n",
        "\n",
        "\n",
        "model = make_or_restore_model()\n",
        "callbacks = [\n",
        "    # This callback saves a SavedModel every 100 batches.\n",
        "    # We include the training loss in the saved model name.\n",
        "    keras.callbacks.ModelCheckpoint(\n",
        "        filepath=checkpoint_dir + \"/ckpt-loss={loss:.2f}\", save_freq=100\n",
        "    )\n",
        "]\n",
        "model.fit(x_train, y_train, epochs=1, callbacks=callbacks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "svOMLNI3mjli"
      },
      "source": [
        "您还可以编写自己的回调来保存和恢复模型。\n",
        "\n",
        "有关序列化和保存的完整指南，请参阅[保存和序列化模型](https://tensorflow.google.cn/guide/keras/save_and_serialize/)指南。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bg0pkgGN7FXf"
      },
      "source": [
        "## 使用学习率时间表\n",
        "\n",
        "训练深度学习模型的常见模式是随着训练的进行逐渐减少学习。这通常称为“学习率衰减”。\n",
        "\n",
        "学习衰减时间表可以是静态的（根据当前周期或当前批次索引提前确定），也可以是动态的（响应模型的当前行为，尤其是验证损失）。\n",
        "\n",
        "### 将时间表传递给优化器\n",
        "\n",
        "通过将时间表对象作为优化器中的 `learning_rate` 参数传递，您可以轻松使用静态学习率衰减时间表："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8o5pkAe1QTyy"
      },
      "outputs": [],
      "source": [
        "initial_learning_rate = 0.1\n",
        "lr_schedule = keras.optimizers.schedules.ExponentialDecay(\n",
        "    initial_learning_rate, decay_steps=100000, decay_rate=0.96, staircase=True\n",
        ")\n",
        "\n",
        "optimizer = keras.optimizers.RMSprop(learning_rate=lr_schedule)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mmYju7UaKXWT"
      },
      "source": [
        "提供了几个内置时间表：`ExponentialDecay`、`PiecewiseConstantDecay`、`PolynomialDecay` 和 `InverseTimeDecay`。\n",
        "\n",
        "### 使用回调实现动态学习率时间表\n",
        "\n",
        "由于优化器无法访问验证指标，因此无法使用这些时间表对象来实现动态学习率时间表（例如，当验证损失不再改善时降低学习率）。\n",
        "\n",
        "但是，回调确实可以访问所有指标，包括验证指标！因此，您可以通过使用可修改优化器上的当前学习率的回调来实现此模式。实际上，它甚至以 `ReduceLROnPlateau` 回调的形式内置。"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lOx7m1rNykV5"
      },
      "source": [
        "## 可视化训练期间的损失和指标\n",
        "\n",
        "在训练期间密切关注模型的最佳方法是使用 [TensorBoard](https://tensorflow.google.cn/tensorboard)，这是一个基于浏览器的应用，它可以在本地运行，为您提供：\n",
        "\n",
        "- 训练和评估的实时损失和指标图\n",
        "- （可选）层激活直方图的可视化\n",
        "- （可选）`Embedding` 层学习的嵌入空间的 3D 可视化\n",
        "\n",
        "如果您已通过 pip 安装了 TensorFlow，则应当能够从命令行启动 TensorBoard：\n",
        "\n",
        "```\n",
        "tensorboard --logdir=/full_path_to_your_logs\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3SMAHA0zgb4r"
      },
      "source": [
        "### 使用 TensorBoard 回调\n",
        "\n",
        "将 TensorBoard 与 Keras 模型和 fit 方法一起使用的最简单方式是 `TensorBoard` 回调。\n",
        "\n",
        "在最简单的情况下，只需指定您希望回调写入日志的位置即可："
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "sJSgiVW4EVNA"
      },
      "outputs": [],
      "source": [
        "keras.callbacks.TensorBoard(\n",
        "    log_dir=\"/full_path_to_your_logs\",\n",
        "    histogram_freq=0,  # How often to log histogram visualizations\n",
        "    embeddings_freq=0,  # How often to log embedding visualizations\n",
        "    update_freq=\"epoch\",\n",
        ")  # How often to write logs (default: once per epoch)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Otu2i1gbeymg"
      },
      "source": [
        "有关更多信息，请参阅 [`TensorBoard` 回调的文档](https://tensorflow.google.cn/api_docs/python/tf/keras/callbacks/tensorboard/)。"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "train_and_evaluate.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
